<template>
	<view class="page-change-background photo-operator">
		<view class="fixed-top-tab">
			<switch-tab :current="currentTab" :list="topTabs" @change="onTopTabChange"></switch-tab>
		</view>

		<view class="top-container flex-center">
			<template v-if="photoUrl">
				<!-- 单张 -->
				<view v-if="currentTab === 0" class="photo-wrap">
					<text class="photo-witdh">{{ showSize.width }}{{ showSize.unit }}</text>
					<text class="photo-height">{{ showSize.height }}{{ showSize.unit }}</text>
					<image class="photo-image" :style="photoImageStyle" :src="photoUrl" mode="aspectFit"></image>
				</view>
				<!-- 排版照 -->
				<view v-else class="typeset-photo-wrap">
					<image class="typeset-photo-image" :src="typesetUrl"></image>
				</view>

				<view class="reupload-button custom-button white-btn-gray-text" @tap="onChoosePhoto">
					<u-button type="primary" shape="circle" text="重新上传"></u-button>
				</view>

			</template>
			<template v-else>
				<view class="upload-box" @tap="onChoosePhoto">
					<text class="add-icon">+</text>
					<view class="add-text">点击上传你的照片</view>
				</view>
			</template>

			<artificial-beauty />

		</view>

		<view class="field-container">
			<view class="tab-container">
				<u-tabs :list="tabs" :scrollable="false" @change="onTabChange" lineWidth="28"
					itemStyle="width:340rpx;height:66rpx;box-sizing:border-box;align-items: flex-start;"></u-tabs>
			</view>
			<view v-show="currentFuncIdx === 0" class="choose-color-container">
				<choose-color :current="backColor" :onColorChange="onColorChange"
					@backColorListChange="onBackColorListChange" />
			</view>
			<view v-show="currentFuncIdx === 1" class="choose-size-container">
				<choose-size ref="chooseSizeRef" :current="currentSize.mm" @change="onSizeChange" />
			</view>
			<view class="btn-double">
				<view class="custom-button full-button" @tap="onSavePhoto">
					<!-- 未上传图片时禁用 -->
					<u-button type="primary" shape="circle" :disabled="!userImage" text="保存电子照"></u-button>
				</view>
				<!-- #ifndef MP-TOUTIAO -->
					<view class="custom-button full-button" @tap="onPrintMail">
						<!-- 未上传图片或者自定义尺寸时禁用 -->
						<u-button type="primary" shape="circle" :disabled="!userImage || currentSize.custom"
							text="冲印邮寄"></u-button>
					</view>
				<!-- #endif -->
			</view>
		</view>
	</view>

	<view style="visibility: hidden;position: fixed; top: 200vh">
		<image :src="tempImage" @load="onImageLoad"></image>
	</view>
</template>
<script setup>
	import {
		onLoad,
		onReachBottom,
	} from '@dcloudio/uni-app';
	import {
		ref,
		reactive,
		computed,
	} from "vue";
	import ArtificialBeauty from '@/components/artificial-beauty/artificial-beauty.vue';
	import ChooseColor from '@/components/choose-color/choose-color.vue';
	import ChooseSize from '@/components/choose-size/index.vue';
	import SwitchTab from '@/components/switch-tab/index.vue';
	import {
		getFileSize,
		pxTomm,
		uploadFile
	} from '@/common/js/method.js';

	// 用户上传的图片
	const userImage = ref('');
	const tempImage = ref(''); // 临时存储上传的url,用于图片加载后裁剪
	const photoUrl = ref(''); // 单张照地址
	const typesetUrl = ref(''); //排版照地址
	const photoUrls = ref({});
	const photoKeys = ref({});
	const typesetUrls = ref({});
	const currentTab = ref(0);
	const backColor = ref('#FFFFFF');
	const chooseSizeRef = ref(null);
	const topTabs = ['单张', '排版照'];

	const tabs = [{
		name: '选择底色',
	}, {
		name: '选择尺寸',
	}];
	const busiType = ref('change-background');

	const backgroundList = ref(null);
	// 默认选中一寸照
	const currentSize = ref({
		id: 1,
		specId: 1,
		minSize: 100,
		maxSize: 200,
		dpi: 300,
		name: "一寸",
		mm: '25x35',
		px: '295x413',
		unit: 'px',
	});

	const showSize = computed(() => {
		const unit = currentSize.value.unit;
		return {
			width: currentSize.value[unit].split('x')[0],
			height: currentSize.value[unit].split('x')[1],
			unit,
		}
	});
	const photoImageStyle = computed(() => {
		const width = +currentSize.value.px.split('x')[0];
		const height = +currentSize.value.px.split('x')[1];
		let large = width > height ? width : height; //取较长的一边
		let scale = large < 250 ? 1 : 250 / large; //较长边大于250px则缩放，另一边也按该比例缩放
		return {
			width: width * scale + 'px',
			height: height * scale + 'px',
		}
	})


	// 获取颜色列表
	const onBackColorListChange = (list) => {
		backgroundList.value = list.map(item => item.background);
	}

	// 证件照环境检测接口
	const checkFunc = async (onlineUrl) => {
		await uni.$request('/api/busi/photo/check', {
			specId: currentSize.value.specId,
			imageUrl: onlineUrl,
		});
	}
	const getCustomFileSize = async (src) => {
		if (!currentSize.value.custom) {
			return;
		}
		const fileSize = await getFileSize(src);
		console.log('fileSize', fileSize)
		currentSize.value.minSize = fileSize;
		currentSize.value.maxSize = fileSize;
	}

	const setPhotoInfo = () => {
		photoUrl.value = photoUrls.value[backColor.value];
		typesetUrl.value = typesetUrls.value[backColor.value];
		currentSize.value.photoKey = photoKeys.value[backColor.value];
		getCustomFileSize(photoUrl.value);
	}
	const resetImageCache = () => {
		photoUrls.value = {};
		typesetUrls.value = {};
		photoKeys.value = {};
	}

	const preview = async (color) => {
		color = color || backgroundList.value.join(',');
		const [widthPixel, heightPixel] = currentSize.value.px.split('x');

		const payload = currentSize.value.custom ? {
			specId: 12, //自定义照片id固定送12
			width: widthPixel,
			height: heightPixel,
			imageUrl: userImage.value,
			bkColor: backColor.value,
		} : { //固定尺寸
			specId: currentSize.value.specId,
			imageUrl: userImage.value,
			bkColor: color,
		}
		const res = await uni.$request('/api/busi/photo/preview', payload);
		// 缓存所有颜色的图片
		photoUrls.value = {
			...photoUrls.value,
			...res.data.previewUrls
		};
		typesetUrls.value = {
			...typesetUrls.value,
			...res.data.typesetUrls
		};
		// 缓存普通照片的key
		Object.keys(photoUrls.value).forEach((color) => {
			photoKeys.value[color] = res.data.photoKey; // 保存颜色与key对应关系
		})
		setPhotoInfo();
	}

	const uploadImage = async (localImage) => {
		// 上传照片到oss
		userImage.value = await uploadFile(localImage);
		// 调用环境检测接口
		await checkFunc(userImage.value);
		// 预览接口
		await preview()
	};

	const onImageLoad = async (e) => {
		// 如果是自定义,且用户没有设置大小
		if (+e.detail.width > 2000 || +e.detail.height > 2000) {
			uni.$u.toast('图片宽/高过大，不能超过2000px')
			return;
		}
		// 校验通过
		await uploadImage(tempImage.value);
	}

	const onChoosePhoto = () => {
		uni.chooseImage({
			count: 1, //默认9
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			// sourceType: ['album'], //从相册选择
			success: function(res) {
				resetImageCache();
				uploadImage(res.tempFilePaths[0]);
			}
		});
	};


	const onTopTabChange = (index) => {
		if (!userImage.value) {
			uni.$u.toast('请先上传照片');
			return;
		}

		if (currentSize.value.custom) {
			uni.$u.toast('自定义尺寸暂不支持排版照');
			return;
		}
		currentTab.value = index;
	}

	// 检查是否已缓存该颜色图片（区分美颜和无美颜存储）
	const getPhotoUrlByColor = (color) => {
		let res = null;
		if (photoUrls.value[color]) {
			res = {
				photoUrl: photoUrls.value[color],
				typesetUrl: typesetUrls.value[color],
			}
		}
		return res;
	}


	const setPhotoUrlByColor = async () => {
		// 如果当前背景色的图片不存在，调预览接口查询
		if (!photoUrls.value[backColor.value]) {
			preview(backColor.value);
		} else {
			setPhotoInfo();
		}

	}

	const onColorChange = (color) => {
		backColor.value = color;
		if (!userImage.value) return;
		setPhotoUrlByColor();
	}


	const onSizeChange = (item) => {
		console.log('onSizeChange', item)
		currentSize.value = {
			id: item.id,
			specId: item.specId,
			minSize: item.minSize,
			maxSize: item.maxSize,
			dpi: item.dpi,
			custom: item.custom,
			mm: item.value,
			px: item.px,
			unit: item.unit,
		};
		if (!userImage.value) {
			// uni.$u.toast('请先上传照片');
			return;
		}
		preview();
	}

	const onSavePhoto = () => {
		// 未上传图片
		if (!userImage.value) return;
		const [widthPixel, heightPixel] = currentSize.value.px.split('x');
		const data = {
			...currentSize.value,
			widthPixel,
			heightPixel,
			backColor: backColor.value, //背景色
			photoUrl: encodeURIComponent(getPhotoUrlByColor(backColor.value).photoUrl), //单张照
			typesetUrl: encodeURIComponent(getPhotoUrlByColor(backColor.value).typesetUrl), //排版照
		};

		uni.navigateTo({
			url: `/pages/make-photo/make-photo-save?type=${busiType.value}&data=${JSON.stringify(data)}`
		})

	}


	const onPrintMail = () => {
		// 未上传图片
		if (!userImage.value) return;
		// 自定义尺寸不支持冲印邮寄
		if (currentSize.value.custom) {
			return;
		}
		const [widthPixel, heightPixel] = currentSize.value.px.split('x');
		const data = {
			...currentSize.value,
			widthPixel,
			heightPixel,
			backColor: backColor.value, //背景色
			typesetUrl: encodeURIComponent(getPhotoUrlByColor(backColor.value).typesetUrl), //排版照
		};
		uni.navigateTo({
			url: `/pages/make-photo/make-photo-print?type=${busiType.value}&data=${JSON.stringify(data)}`
		})
	}
	const currentFuncIdx = ref(0);

	const onTabChange = ({
		index,
		...tabItem
	}) => {
		currentFuncIdx.value = index;
		// if (index === 0) {

		// } else if (index === 1) {

		// } else if (index === 2) {

		// }
	}
	const handleContact = () => {

	}
</script>

<style lang="scss" scoped>
	@import "@/common/style/photo-operator.scss";

	.page-change-background {}
</style>